<template>
  <div class="page">
    <div class="page-wrapper">
      <div class="header">
        <div class="company">
          <div class="company-image">{{ data.name }}</div>
          <div class="company-info">
            <div class="company-name">{{ pageValue.ceEtpname }}</div>
            <div class="company-desc">
              <el-tag
                v-if="pageValue.cusScaleId"
                class="company-tag"
                size="small"
                type="success"
              >
                {{ cusScaleIdFilter }}
              </el-tag>
              <el-tag
                v-if="pageValue.custype"
                class="company-tag"
                size="small"
                type="primary"
              >
                {{ custypeFilter }}
              </el-tag>
              <el-rate
                v-if="pageValue.xj"
                class="rate"
                disabled
                v-model="pageValue.xj"
              />
            </div>
          </div>
        </div>
        <div class="manager" v-if="pageValue.khjlname">
          <div class="manager-image"></div>
          <div>
            <div class="manager-label">{{ pageValue.khjlname }}</div>
            <div>
              <span class="manager-label">工号：</span>
              <span class="manager-value">{{ pageValue.khjlid }}</span>
            </div>
            <div>
              <span class="manager-label">电话：</span>
              <span class="manager-value">{{ pageValue.khjlmobile }}</span>
            </div>
          </div>
        </div>
        <div class="opera">
          <el-button size="small" type="primary" @click="orderModify"
            >修改</el-button
          >
          <el-button size="small" type="primary" @click="handleToOrder"
            ><el-icon><ShoppingCart /></el-icon
          ></el-button>
          <el-button size="small"
            ><el-icon><Star /></el-icon>
            <span style="{{ margin-left: '5px' }}">去服务</span></el-button
          >
        </div>
      </div>
      <el-collapse v-model="data.activeNames" @change="handleChange">
        <el-collapse-item class="collapse" name="1">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">基础信息</span>
          </template>
          <el-row
            class="row"
            v-for="(row, index) in data.base"
            :key="'row' + index"
          >
            <div v-for="col in row" :key="col.id">
              <el-col class="col" :span="4">
                <div
                  v-if="col.label === 'classifyname2'"
                  class="item item-label"
                >
                  {{ pageValue.classifyname2 }}
                </div>
                <div v-else class="item item-label">{{ col.label }}</div>
              </el-col>
              <el-col class="col" :span="4">
                <div class="item item-value">
                  {{ pageValue[col.id] }}
                  <span v-if="col.id === 'ceRegmoney'">万元</span>
                </div>
              </el-col>
            </div>
          </el-row>
        </el-collapse-item>
        <el-collapse-item class="collapse" name="2">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">联系方式</span>
          </template>
          <el-table
            class="table-content"
            :data="data.contact2"
            :header-cell-style="{ fontSize: '12px', padding: '0' }"
            :cell-style="{ fontSize: '12px', padding: '8px 0' }"
            border
          >
            <el-table-column prop="label" align="center" min-width="17%">
              <template v-slot="scoped">
                企业联系人{{ scoped.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              align="center"
              min-width="33%"
            >
              <template v-slot="scoped">
                {{ pageValue[scoped.row.name] }}
              </template>
            </el-table-column>
            <el-table-column
              prop="work"
              align="center"
              label="职务"
              min-width="17%"
            >
              <template v-slot="scoped">
                {{ pageValue[scoped.row.work] }}
              </template>
            </el-table-column>
            <el-table-column
              prop="phone"
              align="center"
              label="联系电话"
              min-width="33%"
            >
              <template v-slot="scoped">
                {{ pageValue[scoped.row.phone] }}
              </template>
            </el-table-column>
          </el-table>
          <el-row
            class="row"
            v-for="(row, index) in data.contact"
            :key="'row' + index"
          >
            <div v-for="col in row" :key="col.id">
              <el-col class="col" :span="4">
                <div class="item item-label">{{ col.label }}</div>
              </el-col>
              <el-col class="col" :span="4">
                <div class="item item-value">{{ pageValue[col.id] }}</div>
              </el-col>
            </div>
          </el-row>
        </el-collapse-item>
        <el-collapse-item
          class="collapse"
          name="3"
          v-if="pageValue.custype === '1'"
        >
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">代账公司专属信息</span>
          </template>
          <el-row
            class="row"
            v-for="(row, index) in data.agency"
            :key="'row' + index"
          >
            <div v-for="col in row" :key="col.id">
              <el-col class="col" :span="4">
                <div class="item item-label">{{ col.label }}</div>
              </el-col>
              <el-col class="col" :span="4">
                <el-button
                  v-if="col.type === 'download'"
                  style="padding: 0"
                  size="small"
                  class="item item-value"
                  type=""
                  text
                  :disabled="!pageValue[col.id]"
                  @click="handleDownload(pageValue[col.id])"
                >
                  下载
                </el-button>
                <div v-else class="item item-value">
                  {{ pageValue[col.id] }}
                </div>
              </el-col>
            </div>
          </el-row>
        </el-collapse-item>

        <el-collapse-item name="4" v-if="pageValue.custype === '1'">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">代账公司下属企业信息</span>
          </template>
          <div style="margin-bottom: 15px">
            <el-button
              size="small"
              type="danger"
              :disabled="data.agencySelection.length === 0"
              @click="handleAgencyDeleteBranch"
            >
              删除企业
            </el-button>
            <el-divider direction="vertical" />
            <el-button
              size="small"
              style="margin-left: 3px"
              @click="data.importDialogVisible = true"
            >
              批量导入
            </el-button>
            <el-button size="small" style="margin-right: 3px" disabled>
              导出
            </el-button>
            <el-divider direction="vertical" />
            <el-button
              size="small"
              style="margin-left: 3px"
              :disabled="data.agencySelection.length === 0"
              @click="handleUpdateFrStatue(true)"
            >
              确认分润
            </el-button>
            <el-button
              size="small"
              style="margin-right: 3px"
              :disabled="data.agencySelection.length === 0"
              @click="handleUpdateFrStatue(false)"
            >
              反选分润
            </el-button>
            <el-divider direction="vertical" />
            <div style="display: inline-block; margin-left: 3px">
              <el-input
                clearable
                v-model="data.queryParams.keyword"
                placeholder="请输入税号或名称"
                style="width: 143px; margin-right: 3px"
                size="small"
              />

              <el-select
                style="width: 135px; margin-right: 3px"
                size="small"
                clearable
                v-model="data.queryParams.jyzt"
                placeholder="请选择到账情况"
              >
                <el-option
                  v-for="item in data.jyztOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>

              <el-select
                style="width: 135px; margin-right: 3px"
                size="small"
                clearable
                v-model="data.queryParams.frzt"
                placeholder="请选择分润情况"
              >
                <el-option
                  v-for="item in data.frztOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>

              <el-button size="small" type="primary" @click="customerList"
                >查询</el-button
              >
            </div>
          </div>
          <el-table
            :data="data.agencyCompanyList"
            border
            style="width: 100%"
            @selection-change="agencySelectionChange"
          >
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column
              prop="custName"
              label="公司名称"
              width="180"
              align="center"
            />
            <el-table-column
              prop="taxCode"
              label="税号"
              width="120"
              align="center"
            />
            <el-table-column prop="jyje" label="到账金额" align="center" />
            <el-table-column prop="jyzt" label="到账情况" align="center">
              <template v-slot="scoped">{{
                jyFilter(scoped.row.jyzt)
              }}</template>
            </el-table-column>
            <el-table-column
              prop="dqsj"
              label="服务到期时间"
              width="180"
              align="center"
            />
            <el-table-column prop="frzt" label="分润情况" align="center">
              <template v-slot="scoped">{{
                frFilter(scoped.row.frzt)
              }}</template>
            </el-table-column>
            <el-table-column prop="custType" label="企业性质" align="center">
              <template v-slot="scoped">
                {{ ScaleIdFilter(scoped.row.custType) }}
              </template>
            </el-table-column>
            <!--            <el-table-column prop="remark" label="备注" align="center"/>-->
            <!--            <el-table-column width="100" label="操作" align="center">-->
            <!--              <template slot-scope="scoped">-->
            <!--                <el-popconfirm-->
            <!--                  title="确定删除下属代账公司信息吗？"-->
            <!--                  @confirm="handleAgencyDelete(scoped.row.cusId)"-->
            <!--                >-->
            <!--                  <el-button-->
            <!--                    size="small"-->
            <!--                    type="text"-->
            <!--                    slot="reference"-->
            <!--                  >-->
            <!--                    删除-->
            <!--                  </el-button>-->
            <!--                </el-popconfirm>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
          <Pagination
            class="pagination"
            :total="total"
            v-model:page="data.queryParams.pageNum"
            v-model:limit="data.queryParams.pageSize"
            @pagination="customerList"
          />
        </el-collapse-item>

        <el-collapse-item name="5">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">服务记录</span>
          </template>
          <el-table :data="serviceRecordList" border style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            />
            <el-table-column prop="date" label="服务单号" align="center" />
            <el-table-column prop="name" label="物品名称" align="center" />
            <el-table-column prop="address" label="服务人员" align="center" />
            <el-table-column
              prop="address"
              label="服务到期日期"
              align="center"
            />
            <el-table-column prop="address" label="服务日期" align="center" />
            <el-table-column
              prop="address"
              label="是否产生投诉"
              align="center"
            />
            <el-table-column
              prop="address"
              label="问题明细及解决办法"
              align="center"
            />
          </el-table>
          <Pagination
            class="pagination"
            :total="total"
            v-model:page="data.serverQueryParams.pageNum"
            v-model:limit="data.serverQueryParams.pageSize"
            @pagination="pagination"
          />
        </el-collapse-item>
        <el-collapse-item name="6">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">购买记录</span>
          </template>
          <el-table :data="data.purchaseRecordList" border style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            />
            <el-table-column prop="orderId" label="订单编号" align="center" />
            <el-table-column prop="matName" label="物品名称" align="center" />
            <el-table-column prop="matNum" label="数量" align="center" />
            <el-table-column prop="unitPrice" label="单价" align="center" />
            <el-table-column prop="amount" label="金额" align="center" />
            <el-table-column
              prop="salespersonName"
              label="销售人员"
              align="center"
            />
            <el-table-column prop="billNo" label="发票号码" align="center" />
            <el-table-column prop="buyTime" label="购买日期" align="center" />
            <el-table-column
              prop="expireTime"
              label="服务到期日期"
              align="center"
            />
            <el-table-column prop="address" label="合同附件" align="center" />
            <el-table-column prop="remark" label="备注" align="center" />
          </el-table>
          <Pagination
            class="pagination"
            :total="data.totalLineCustomer"
            v-model:page="data.purchaseQueryParams.pageNum"
            v-model:limit="data.purchaseQueryParams.pageSize"
            @pagination="data.pagination"
          />
        </el-collapse-item>
        <el-collapse-item name="7">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">权益记录</span>
          </template>
          <el-table :data="data.rightsRecordList" border style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            />
            <el-table-column prop="date" label="权益类型" align="center" />
            <el-table-column prop="name" label="权益数量" align="center" />
            <el-table-column prop="address" label="使用时间" align="center" />
            <el-table-column prop="address" label="使用数量" align="center" />
            <el-table-column
              prop="address"
              label="权益到期日期"
              align="center"
            />
            <el-table-column prop="address" label="备注" align="center" />
          </el-table>
          <Pagination
            class="pagination"
            :total="total"
            v-model:page="data.rightsQueryParams.pageNum"
            v-model:limit="data.rightsQueryParams.pageSize"
            @pagination="data.pagination"
          />
        </el-collapse-item>
        <el-collapse-item name="8">
          <template v-slot:title>
            <div class="block"></div>
            <span class="collapse-title">客户分析</span>
          </template>
          <div
            id="myChart"
            style="width: 350px; height: 350px; margin-top: 30px"
          ></div>
        </el-collapse-item>
      </el-collapse>
      <el-dialog
        title="新增下属企业信息"
        v-if="data.dialogVisible"
        v-model="data.dialogVisible"
        width="1000px"
      >
        <div class="dialog-height">
          <customer-order :dzjg="pageValue" ref="order" />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleCreateCustomer"
              >保 存</el-button
            >
          </span>
        </template>
      </el-dialog>
      <el-dialog
        title="批量导入下属企业信息"
        v-if="data.importDialogVisible"
        v-model="data.importDialogVisible"
        width="400px"
      >
        <el-upload
          ref="upload"
          v-loading="data.upload.isUploading"
          element-loading-text="正在上传模板 请稍候"
          :limit="1"
          action="#"
          :http-request="requestUpload"
          accept=".xlsx"
          :disabled="data.upload.isUploading"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip" style="color: red">
              提示：仅允许导入“xlsx”格式文件！
              <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="fetchFile"
                >下载模板</el-link
              >
            </div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.importDialogVisible = false"
              >取 消</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="CustomerDetail">
import {
  fetchCustomerDetail,
  fetchCustomerServiceList,
  fetchCustomerList,
  fetchBranchCustomerList,
  lineCustomerList,
  deleteCustomer,
  deleteCustomerBatch,
  importAgencyCompany,
  updateFrStatus
} from '@/api/customer/customer'

import * as echarts from 'echarts'
import arr from '@/views/erp/customerData/modules/logoinfo'
import CustomerOrder from '@/views/erp/customerDetail/modules/CustomerOrder'
import { reactive, toRefs, getCurrentInstance, computed } from 'vue'
import { useRouter } from 'vue-router'
import 'echarts/theme/macarons.js'
const router = useRouter()
const { proxy } = getCurrentInstance()
// require('echarts/theme/macarons') // echarts theme

const animationDuration = 60

const data = reactive({
  jyztOptions: [
    {
      value: '0',
      label: '未成功'
    },
    {
      value: '1',
      label: '已成功'
    }
  ],
  frztOptions: [
    {
      value: '0',
      label: '未分润'
    },
    {
      value: '1',
      label: '已分润'
    }
  ],
  name: null,
  agencySelection: [],
  dialogVisible: false,
  importDialogVisible: false,
  upload: {
    isUploading: false
  },
  activeNames: ['1', '2', '3', '4'],
  base: [
    [
      { label: '纳税人识别号', id: 'ceTaxcode' },
      { label: '企业名称', id: 'ceEtpname' },
      { label: '注册资本', id: 'ceRegmoney' }
    ],
    [
      { label: '所属地区', id: 'cityCn' },
      { label: '所属片区', id: 'regionCn' },
      { label: '所属税务机关', id: 'ceTaxbureaname' }
    ],
    [
      { label: '客户分类', id: 'classifyname1' },
      { label: 'classifyname2', id: 'classifyname3' },
      { label: '', id: '' }
    ]
  ],
  contact2: [
    { name: 'ceContactname', work: 'linkwork', phone: 'ceContactmobile1' },
    {
      name: 'ceContactname2',
      work: 'linkwork2',
      phone: 'ceContactmobile1'
    },
    {
      name: 'ceContactname3',
      work: 'linkwork3',
      phone: 'ceContactmobile1'
    }
  ],
  contact: [
    // [
    //   { label: '企业联系人1', id: 'ceContactname'},
    //   { label: '联系人职务', id: 'linkwork'},
    //   { label: '企业联系人2', id: 'ceContactname2'},
    // ],[
    //   { label: '联系电话1', id: 'ceContactmobile1'},
    //   { label: '联系电话2', id: 'ceContactmobile2'},
    //   { label: '联系电话3', id: 'ceContactmobile3'},
    // ],
    [
      { label: '企业地址', id: 'ceOfficeaddr' },
      { label: '银行名称', id: 'ceCreatebank' },
      { label: '银行行号', id: 'ceBankaccount' }
    ]
  ],
  agency: [
    [
      { label: '代账公司授权码', id: 'sqm' },
      { label: '代账公司星级', id: 'xj' },
      { label: '星级授牌时间', id: 'spsj' }
    ],
    [
      { label: '星级授权到期时间', id: 'spdqsj' },
      { label: '代账公司规模', id: 'dzgm' },
      { label: '代账公司每户分润金额', id: 'frje' }
    ],
    [
      { label: '代账公司每户收取金额', id: 'sqje' },
      { label: '代账公司合同协议上传', id: 'htxy', type: 'download' },
      { label: '代账公司授牌照片上传', id: 'spzp', type: 'download' }
    ],
    [
      { label: '预计总收益', id: 'yjzsy' },
      { label: '预计分润金额', id: 'yjfrzje' },
      { label: '实际收益', id: 'sjsy' }
    ],
    [
      { label: '实际分润', id: 'sjfr' },
      { label: '收取率', id: 'sqlv' },
      { label: '', id: '' }
    ]
  ],

  // agencySearch: '',
  pageValue: {
    ceBankaccount: null,
    ceContactmobile1: null,
    ceContactmobile2: null,
    ceContactmobile3: null,
    ceContactname: null,
    ceContactname2: null,
    ceCreatebank: null,
    ceOfficeaddr: null,
    ceRegmoney: null,
    ceTaxbureaid: null,
    ceTaxbureaname: null,
    ceTaxcode: null,
    cityCn: null,
    citycodes: null,
    cusClassifyOne: null,
    cusClassifyThree: null,
    cusClassifyTwo: null,
    cusId: null,
    cusScaleId: null,
    cuslevel: null,
    cuslevelName: null,
    custype: null,
    dzgm: null,
    frmoney: null,
    htxy: null,
    khjlid: null,
    khjlmobile: null,
    khjlname: null,
    khjltx: null,
    linkwork: null,
    orgId: null,
    orgName: null,
    region: null,
    regionCn: null,
    spdqsj: null,
    spsj: null,
    spzp: null,
    sqmoney: null,
    xj: null
  },

  agencyCompanyList: [],
  serviceRecordList: [],
  purchaseRecordList: [],
  rightsRecordList: [],

  total: 0,
  totalLineCustomer: 0,
  queryParams: {
    keyword: null,
    jyzt: null,
    frzt: null,
    pageNum: 1,
    pageSize: 10
  },

  purchaseQueryParams: {
    pageNum: 1,
    pageSize: 10,
    cusId: router.currentRoute.value.query.cusId
  },

  rightsQueryParams: {
    pageNum: 1,
    pageSize: 10
  },

  serverQueryParams: {
    pageNum: 1,
    pageSize: 10
  }
})

const custypeFilter = computed(() => {
  const filter = {
    0: '一般产品客户',
    1: '代账公司',
    2: '重点客户'
  }
  return filter[pageValue.value.custype]
})

const cusScaleIdFilter = computed(() => {
  const filter = {
    0: '一般纳税人',
    1: '小规模纳税人',
    2: '点下户',
    3: '非纳税人'
  }
  return filter[pageValue.value.cusScaleId]
})

const { pageValue } = toRefs(data)
init()

async function init() {
  if (
    !router.currentRoute.value.query ||
    !router.currentRoute.value.query.cusId
  ) {
    proxy.$modal.msgWarning('请先选择客户进入档案明细页')
    router.replace({ path: '/xs/khda' })
  } else {
    await customerDetail()
    await customerList()
    await lineCustomerListT()
  }
  proxy.$nextTick(() => {
    initChart()
  })
}

// mounted() {
//   proxy.$nextTick(() => {
//     data.initChart()
//   })
// }
const ScaleIdFilter = val => {
  const filter = {
    0: '一般纳税人',
    1: '小规模纳税人',
    2: '点下户',
    3: '非纳税人'
  }
  return filter[val]
}
const frFilter = function (val) {
  const filter = {
    0: '未分润',
    1: '已分润'
  }
  return filter[val]
}
const jyFilter = function (val) {
  const filter = {
    0: '未成功',
    1: '已成功'
  }
  return filter[val]
}
function agencySelectionChange(val) {
  data.agencySelection = val
}

async function handleUpdateFrStatue(status) {
  const frzt = status ? '1' : '0'
  const datas = []
  data.agencySelection.forEach(item => {
    datas.push(item.id)
  })
  try {
    const res = await updateFrStatus({ ids: datas, frzt })
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${status ? '确认' : '反选'}分润状态成功`)
      await customerList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('更新分润状态服务异常 请重试')
  }
}

async function handleAgencyDeleteBranch() {
  const datas = []
  data.agencySelection.forEach(item => {
    datas.push(item.id)
  })
  try {
    const res = await deleteCustomerBatch({ ids: datas })
    if (res.code === 200) {
      proxy.$modal.msgSuccess('删除成功')
      await customerList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('删除代账公司服务异常 请重试')
  }
}

async function requestUpload(data) {
  data.upload.isUploading = true
  let formData = new FormData()
  formData.append('file', data.file)
  formData.append('parentId', router.currentRoute.value.query.cusId + '')
  try {
    const res = await importAgencyCompany(formData)
    if (res.code === 200) {
      console.log(res)
    } else {
      proxy.$modal.msgError(res.msg)
    }
    data.upload.isUploading = false
    data.importDialogVisible = false
    // data.loading = true
    await customerList()
    // data.loading = false
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('上传文件服务异常 请重试')
    data.upload.isUploading = false
  }
}

function initData() {
  let province = arr.province // xx省 json数据
  let cities = arr.cities // xx市 json数据
  let companySuffixes = arr.company_suffixes // xxxx 后缀json数据

  let length = data.name.length // name值为以上列举的企业名称
  if (length <= 4) {
    return data.name
  }

  let nameList = [] // 储存企业名称过滤后的字符串数组集合
  for (let i = 0; i < province.length; i++) {
    let prefix = province[i]
    if (data.name.startsWith(prefix)) {
      // 以 xxxx省 开头
      let nameSub = data.name.substring(prefix.length)
      nameList.push(nameSub)
    } else {
      nameList.push(data.name)
    }
  }
  data.name = getStrLenShort(nameList)
  console.log(data.name)
  let nameList1 = [] // 储存企业名称过滤后的字符串数组集合
  for (let i = 0; i < cities.length; i++) {
    let prefix = cities[i]
    if (data.name.startsWith(prefix)) {
      // 以 xxxx市 开头
      let nameSub = data.name.substring(prefix.length)
      nameList1.push(nameSub)
    } else {
      nameList1.push(data.name)
    }
  }
  data.name = getStrLenShort(nameList1)

  let nameList2 = [] // 储存企业名称过滤后的字符串数组集合
  for (let i = 0; i < companySuffixes.length; i++) {
    let suffix = companySuffixes[i]
    if (data.name.endsWith(suffix)) {
      // 以 xxxx 结尾
      let substring = data.name.substring(0, data.name.length - suffix.length)
      nameList2.push(substring)
    } else {
      nameList2.push(data.name)
    }
  }
  data.name = getStrLenShort(nameList2)

  if (data.name.includes('（')) {
    data.name = data.name.split('（')[0]
  }

  if (data.name.length > 4) {
    data.name = data.name.substring(0, 4)
  }
}

function handleDialogVisible() {
  data.dialogVisible = true
}

function handleCreateCustomer() {
  data.$refs.order.handleSubmit()
  data.dialogVisible = false
}

function handleDownload(url) {
  let image = new Image()
  const urlName = url.split('/')
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = url
  console.log(url)
  window.open(url)

  // image.onload = () => {
  //   let canvas = document.createElement("canvas");
  //   canvas.width = image.width;
  //   canvas.height = image.height;
  //   let ctx = canvas.getContext("2d");
  //   ctx.drawImage(image, 0, 0, image.width, image.height);
  //   canvas.toBlob((blob) => {
  //     let url = URL.createObjectURL(blob);
  //     console.log(url)
  //     console.log(urlName[urlName.length - 1])
  //     data.download(url, urlName[urlName.length - 1]);
  //     // 用完释放URL对象
  //     URL.revokeObjectURL(url);
  //   });
  // };
}

function download(href, name) {
  let eleLink = document.createElement('a')
  eleLink.download = name
  eleLink.href = href
  eleLink.click()
  eleLink.remove()
}

async function handleAgencyDelete(id) {
  try {
    const res = await deleteCustomer({ cus_id: id })
    if (res.code === 200) {
      proxy.$modal.msgSuccess('删除成功')
      await customerList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('删除代账公司服务异常 请重试')
  }
}
async function lineCustomerListT() {
  try {
    const res = await lineCustomerList(data.purchaseQueryParams)
    if (res.code === 200) {
      data.purchaseRecordList = res.rows
      data.totalLineCustomer = res.total
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('查询客户购买记录分页服务异常 请重试')
  }
}

async function customerList() {
  try {
    const res = await fetchBranchCustomerList({
      ...data.queryParams,
      parentId: router.currentRoute.value.query.cusId
    })
    if (res.code === 200) {
      data.agencyCompanyList = res.rows
      data.total = res.total
      console.log(data.agencyCompanyList)
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('查询下属企业服务异常 请重试')
  }
}

async function customerDetail() {
  const res = await fetchCustomerDetail(router.currentRoute.value.query.cusId)
  if (res.code === 200) {
    pageValue.value = res.data
    pageValue.value.xj = parseInt(pageValue.value.xj)
    data.name = res.data.ceEtpname
    initData()
  }
}

async function customerServiceTable() {
  const res = await fetchCustomerServiceList(
    router.currentRoute.value.query.cusId
  )
  if (res.code === 200) {
    data.serviceRecordList = res.data
  }
  console.log(res)
}
function handleChange() {}
function getStrLenShort(nameList) {
  let tempName = ''
  if (nameList.length > 0) {
    tempName = nameList[0]
    let temp = ''
    for (let i = 1; i < nameList.length; i++) {
      temp = nameList[i]
      if (tempName.length > temp.length) {
        tempName = temp
      }
    }
  }
  return tempName
}

function initChart() {
  data.chart = echarts.init(document.getElementById('myChart'), 'macarons')

  data.chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    radar: {
      radius: '66%',
      center: ['50%', '42%'],
      splitNumber: 8,
      splitArea: {
        areaStyle: {
          color: 'rgba(127,95,132,.3)',
          opacity: 1,
          shadowBlur: 45,
          shadowColor: 'rgba(0,0,0,.5)',
          shadowOffsetX: 0,
          shadowOffsetY: 15
        }
      },
      indicator: [
        { name: '购买力', max: 10 },
        { name: '服务情况', max: 10 },
        { name: '权益情况', max: 10 },
        { name: '用户忠诚度', max: 10 },
        { name: '客情关系', max: 10 }
      ]
    },
    series: [
      {
        type: 'radar',
        symbolSize: 0,
        areaStyle: {
          normal: {
            shadowBlur: 13,
            shadowColor: 'rgba(0,0,0,.2)',
            shadowOffsetX: 0,
            shadowOffsetY: 10,
            opacity: 1
          }
        },
        data: [{ value: [1, 2, 4, 5, 2] }],
        animationDuration: animationDuration
      }
    ]
  })
}

/** 下载模板操作 */
function fetchFile() {
  window.location.href = 'http://192.168.1.6:9000/erp/model/branch/branch.xlsx'
}

function orderModify() {
  router.push({
    path: '/xs/xgkh',
    query: { cusId: pageValue.value.cusId }
  })
}
function handleToOrder() {
  router.push({
    path: '/xs/xzdd',
    query: { cusId: pageValue.value.cusId }
  })
}
</script>

<style scoped lang="scss">
.page {
  min-height: calc(100vh - 89px);
  height: calc(100vh - 89px);

  .page-wrapper {
    height: 100%;
    padding: 20px 60px;
    overflow-y: scroll;
  }
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 25px;

  .company {
    display: flex;
    align-items: center;
    .company-image {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 15px;
      text-align: center;
      width: 60px;
      min-width: 60px;
      min-height: 60px;
      height: 60px;
      font-size: 18px;
      padding: 6px;
      font-weight: 400;
      user-select: none;
      color: white;
      border-radius: 2px;
      background-color: rgb(47, 119, 204);
    }
    .company-info {
      .company-name {
        font-size: 20px;
        margin-bottom: 10px;
        //font-weight: 600;
        color: rgba(0, 0, 0, 0.6);
      }
      .company-desc {
        * {
          display: inline-block;
        }
        span {
          line-height: 20px;
        }
        .company-tag {
          margin-right: 10px;
        }
      }
    }
  }
  .manager {
    display: flex;
    align-items: center;

    .manager-image {
      width: 60px;
      min-width: 60px;
      min-height: 60px;
      height: 60px;
      margin-right: 15px;
      background-color: #2c3e50;
    }
    .manager-label {
      font-size: 12px;
    }
    .manager-value {
      font-size: 12px;
    }
  }
}

.collapse-title {
  font-weight: 600;
}

.block {
  width: 3px;
  display: inline-block;
  height: 16px;
  background-color: rgb(62, 146, 255);
  margin-right: 8px;
}

.col .item {
  width: 100%;
  overflow-y: hidden;
  overflow-x: auto;
  overflow: -moz-scrollbars-none;
  overflow: -moz-scrollbars-none;
  -webkit-overflow-scrolling: touch;
  border: 1px solid lightgray;
  height: 30px;
  white-space: nowrap;
  border-right: none;
  border-bottom: none;
}
.col .item::-webkit-scrollbar {
  display: none;
}
.row .col:last-child .item {
  border-right: 1px solid lightgray;
}

.collapse .row:last-child .col .item {
  border-bottom: 1px solid lightgray;
}
.collapse .row:last-child {
  margin-bottom: 10px;
}

.item-label,
.item-value {
  text-align: center;
  font-size: 12px;
  line-height: 30px;
}

.dialog-height {
  height: 600px;
  overflow-y: scroll;
}

.item-label {
  background-color: rgb(250, 250, 250);
}

.table-content {
  margin-bottom: 20px;
}

.el-collapse-item__content {
  .el-col-4 {
    max-width: none;
  }
  .row div {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
  }
}
</style>
